import router from "@/router/index";
import store from "@/store";
import Layout from "@/layout/index.vue";
import { Notification } from "element-ui";
import NProgress from "nprogress";
import "nprogress/nprogress.css";

NProgress.configure({ showSpinner: false });
const whiteList = ["/login"];

router.beforeEach(async (to, from, next) => {
  NProgress.start();
  document.title = "Jing后台管理系统";

  // 判断是否登录
  const hasToken = store.state.token.tokenInfo;
  if (hasToken) {
    if (to.path === "/login") {
      // 已经登录后访问登录跳转至首页
      next({ path: "/" });
      NProgress.done();
    } else {
      // 判断是否已经加载过路由
      const hasRoutes = store.getters["user/getMenus"];
      if (hasRoutes) {
        next();
      } else {
        try {
          // 请求路由信息
          await store.dispatch("user/getUser");
          // 过滤路由并动态添加
          onFilterRoutes(to, next, store.getters["user/getMenus"]);
        } catch (error) {
          // 重置token
          store.commit("token/removeToken");

          Notification({
            title: "失败",
            message: error || "动态路由处理失败",
            type: "error",
            position: "bottom-left",
            duration: 3000,
          });
          next("/login");
          NProgress.done();
        }
      }
    }
  } else {
    // 判断是否为白名单请求
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      next("/login");
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});

// 动态添加路由
function onFilterRoutes(to, next, data) {
  const routes = filterRoutes(data);
  routes.forEach((item) => {
    router.options.routes.push(item);
    router.addRoute(item);
  });
  next({ ...to, replace: true });
}

// 过滤路由
function filterRoutes(data) {
  const routes = data.filter((item) => {
    if (item.component === "Layout") {
      item.component = Layout;
    } else {
      item.component = loadView(item.component);
    }

    if (item.children && item.children.length > 0)
      item.children = filterRoutes(item.children);
    return true;
  });
  return routes;
}

// 动态加载路由组件
function loadView(view) {
  return () => import(`@/views/${view}`);
}
